//
//  NewYiJianFanKuiViewController.m
//  wangzhe
//
//  Created by 李 佳伟 on 2018/4/9.
//  Copyright © 2018年 李 佳伟. All rights reserved.
//

#import "NewYiJianFanKuiViewController.h"
#import "JTCSM.h"
#define WIDTH  [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
#define rgb(a,b,c) [UIColor colorWithRed:(a)/255.0f green:(b)/255.0f blue:(c)/255.0f alpha:1]

#define TipString @"请描述您对产品或其他方面的意见，您的建议是我们的产品提升及服务的源泉和动力..."
#define MAX_LIMIT_NUMS 180
@interface NewYiJianFanKuiViewController ()<UITextViewDelegate,UITextFieldDelegate>
@property (nonatomic,strong) UITextView *contentTextView;
@property (nonatomic,strong) UILabel *textNumLab;//文字限制lab
@property (nonatomic,strong) UITextField *phoneTextfield;
@end

@implementation NewYiJianFanKuiViewController

- (void)gotBack{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = NO;
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [df isRemoveTarbar:YES];
    leftBarButtonItems_rightBarButtonItems *leftbtn = KCUSTOMNAVIGSTION_ALLOC;
    self.navigationItem.leftBarButtonItem = [leftbtn setBarButtonItemsImageName:@"fanhui.png" frame:KLeftBarButtonItemFrame_image target:self SEL:@selector(gotBack)];
    [self layoutSubViews];
}

- (void)layoutSubViews{
    
    self.contentTextView = [[UITextView alloc]initWithFrame:CGRectMake(20, 20, KCONTROLLERWith-40, 180)];
    self.contentTextView.textColor = [df colorWithHexString:@"999999" alpha:1];
    self.contentTextView.font = [UIFont systemFontOfSize:14];
    self.contentTextView.text =TipString;
    self.contentTextView.delegate = self;
    [self.view addSubview:self.contentTextView];
    self.textNumLab = [UILabel initWithFrame:CGRectMake(0, KVIEW_Y(self.contentTextView), KCONTROLLERWith-20, 20) text:@"0/180" font:14 textAlignment:NSTextAlignmentRight texcolor:[df colorWithHexString:@"666666" alpha:1] backgroundColor:nil];
    [self.view addSubview:self.textNumLab];
    
    [df newlineViewWithHeightofTop:KVIEW_Y(self.textNumLab)+10 superView:self.view  spacing:0 color:rgb(241, 241, 241) lineHeight:10];
    NSString *str = @"（选填）";
    CGRect rect = [df labelHeightWithContent:str height:50 font:14];
    UILabel *label = [UILabel initWithFrame:CGRectMake(KCONTROLLERWith-rect.size.width-20, KVIEW_Y(self.textNumLab)+10, rect.size.width, 50) text:str font:14 textAlignment:NSTextAlignmentCenter texcolor:[df colorWithHexString:@"999999" alpha:1] backgroundColor:nil];
    [self.view addSubview:label];
    
    self.phoneTextfield = [UITextField initWithframe:CGRectMake(20, KVIEW_Y(self.textNumLab)+10, KCONTROLLERWith-40, 50) backgrandColor:nil placeholder:@"联系电话，方便我们核实相关问题" textAlignment:NSTextAlignmentLeft font:14 texcolor:[df colorWithHexString:@"999999" alpha:1]];
    [_phoneTextfield addTarget:self  action:@selector(valueChanged:)  forControlEvents:UIControlEventAllEditingEvents];
    _phoneTextfield.delegate = self;
    _phoneTextfield.keyboardType=UIKeyboardTypeNumberPad;
    [self.view addSubview:self.phoneTextfield];
    
    UIView *bottomeView = [df newlineViewWithHeightofTop:KVIEW_Y(self.phoneTextfield)+1000 superView:self.view spacing:0 color:rgb(241, 241, 241) lineHeight:1000];
    bottomeView.userInteractionEnabled = YES;
    
    UIButton *tijiaobutton = [UIButton buttonWithType:UIButtonTypeCustom];
    tijiaobutton.frame = CGRectMake(25, KVIEW_Y(self.phoneTextfield)+34, KCONTROLLERWith-40, 50);
    [tijiaobutton addTarget:self action:@selector(tijiao) forControlEvents:UIControlEventTouchUpInside];
    [df layerWithView:tijiaobutton radius:25 width:0 color:nil];
    tijiaobutton.backgroundColor = KZhuTiRGB;
    [tijiaobutton setTitleColor:RGBACOLOR(51, 51, 51, 1) forState:UIControlStateNormal];
    [tijiaobutton setTitle:@"下一步" forState:UIControlStateNormal];
    [self.view addSubview:tijiaobutton];

}
#pragma mark - UITextViewDelegate,用于实现placeholder的效果
- (void)textViewDidBeginEditing:(UITextView *)textView {
    if ([textView.text isEqualToString:TipString]) {
        textView.text = @"";
        textView.textColor=rgb(153, 153, 153);
    }
    textView.textColor=rgb(51, 51, 51);
}
- (void)textViewDidEndEditing:(UITextView *)textView {
    if (textView.text.length<1) {
        textView.text = TipString;
        textView.textColor=rgb(153, 153, 153);
    }else{
        textView.textColor=rgb(51, 51, 51);
    }
}

#pragma mark - 限制输入字数(最多不超过255个字)
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
    //不支持系统表情的输入
    if ([[textView textInputMode] primaryLanguage]==nil||[[[textView textInputMode] primaryLanguage] isEqualToString:@"emoji"]) {
        return NO;
    }
    
    UITextRange *selectedRange = [textView markedTextRange];
    
    //获取高亮部分
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    
    //获取高亮部分内容
    //NSString * selectedtext = [textView textInRange:selectedRange];
    //如果有高亮且当前字数开始位置小于最大限制时允许输入
    if (selectedRange && pos) {
        
        NSInteger startOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.start];
        
        NSInteger endOffset = [textView offsetFromPosition:textView.beginningOfDocument toPosition:selectedRange.end];
        
        NSRange offsetRange = NSMakeRange(startOffset, endOffset - startOffset);
        
        if (offsetRange.location < MAX_LIMIT_NUMS) {
            
            return YES;
        }else{
            return NO;
        }
    }
    
    NSString *comcatstr = [textView.text stringByReplacingCharactersInRange:range withString:text];
    NSInteger caninputlen = MAX_LIMIT_NUMS - comcatstr.length;
    
    if (caninputlen >= 0){
        return YES;
    } else{
        
        NSInteger len = text.length + caninputlen;
        
        //防止当text.length + caninputlen < 0时，使得rg.length为一个非法最大正数出错
        NSRange rg = {0,MAX(len,0)};
        
        if (rg.length > 0){
            
            NSString *s = @"";
            
            //判断是否只普通的字符或asc码(对于中文和表情返回NO)
            BOOL asc = [text canBeConvertedToEncoding:NSASCIIStringEncoding];
            
            if (asc) {
                
                s = [text substringWithRange:rg];//因为是ascii码直接取就可以了不会错
            }else{
                
                __block NSInteger idx = 0;
                __block NSString  *trimString = @"";//截取出的字串
                
                //使用字符串遍历，这个方法能准确知道每个emoji是占一个unicode还是两个
                [text enumerateSubstringsInRange:NSMakeRange(0, [text length])
                                         options:NSStringEnumerationByComposedCharacterSequences
                 
                                      usingBlock: ^(NSString* substring, NSRange substringRange, NSRange enclosingRange, BOOL* stop) {
                                          
                                          if (idx >= rg.length) {
                                              
                                              *stop = YES; //取出所需要就break，提高效率
                                              
                                              return ;
                                          }
                                          trimString = [trimString stringByAppendingString:substring];
                                          idx++;
                                      }];
                s = trimString;
            }
            //rang是指从当前光标处进行替换处理(注意如果执行此句后面返回的是YES会触发didchange事件)
            [textView setText:[textView.text stringByReplacingCharactersInRange:range withString:s]];
            
            //既然是超出部分截取了，那一定是最大限制了。
            self.textNumLab.text = [NSString stringWithFormat:@"%d/%ld",MAX_LIMIT_NUMS,(long)MAX_LIMIT_NUMS];
        }
        return NO;
    }
}

#pragma mark - 显示当前可输入字数/总字数
- (void)textViewDidChange:(UITextView *)textView{
    
    UITextRange *selectedRange = [textView markedTextRange];
    
    //获取高亮部
    UITextPosition *pos = [textView positionFromPosition:selectedRange.start offset:0];
    
    //如果在变化中是高亮部分在变，就不要计算字符了
    if (selectedRange && pos) {
        return;
    }
    
    NSString  *nsTextContent = textView.text;
    NSInteger existTextNum = nsTextContent.length;
    
    if (existTextNum > MAX_LIMIT_NUMS){
        //截取到最大位置的字符(由于超出截部分在should时被处理了所在这里这了提高效率不再判断)
        
        NSString *s = [nsTextContent substringToIndex:MAX_LIMIT_NUMS];
        [textView setText:s];
    }
    
    //不让显示负数
    self.textNumLab.text = [NSString stringWithFormat:@"%ld/%d",MIN(MAX_LIMIT_NUMS,existTextNum),MAX_LIMIT_NUMS];
}
#pragma mark textfieldDelegate
- (void)valueChanged:(UITextField*)textfield{
    
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (range.location >= 11)
        return NO; // return NO to not change text
    return YES;
}

- (void)tijiao{
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.phoneTextfield resignFirstResponder];
    [self.contentTextView resignFirstResponder];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
